/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package jiri

import (
	"os"

	"go.fuchsia.dev/jiri/project"

	"gitee.com/banggua/ggtsync/config"
	"gitee.com/banggua/ggtsync/logger"
)

func isFile(file string) (bool, error) {
	fileInfo, err := os.Stat(file)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		logger.Errorf("%s %v", file, err)
		return false, err
	}
	return !fileInfo.IsDir(), nil
}

func (jc *jiriClient) jiriImport(cfgproj *config.Project) error {
	projectName, manifestName, remoteURL, _ := getArgs(cfgproj.From)

	var (
		manifest *project.Manifest
		jirix    = jc.Xs[cfgproj.Name]
	)
	isExist, err := isFile(jirix.JiriManifestFile())
	if err != nil {
		logger.Errorf("%v %v", cfgproj, err)
		return err
	}

	if isExist {
		m, err := project.ManifestFromFile(jirix, jirix.JiriManifestFile())
		if err != nil {
			logger.Errorf("%v %v", cfgproj, err)
			return err
		}
		manifest = m
	}

	if manifest == nil {
		manifest = &project.Manifest{}
	}

	for _, imp := range manifest.Imports {
		if imp.Manifest == manifestName && imp.Name == projectName && imp.Remote == remoteURL {
			return nil
		}
	}

	manifest.Imports = append(manifest.Imports, project.Import{
		Manifest:     manifestName,
		Name:         projectName,
		Remote:       remoteURL,
		RemoteBranch: "",
		Revision:     "",
		Root:         "",
	})

	err = manifest.ToFile(jirix, jirix.JiriManifestFile())
	if err != nil {
		logger.Errorf("%v %v", cfgproj, err)
		return err
	}
	return nil
}
